import datetime
from applications.models import Message
from applications.common import curd
from applications.common.utils.rights import authorize
from flask import Blueprint, render_template, request
from applications.common.utils.validate import xss_escape
from applications.common.helper import ModelFilter
from applications.models import Message
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.curd import model_to_dicts, enable_status, disable_status
from applications.schemas import MesOutSchema
from flask_login import login_required, current_user
from applications.extensions import db

pest_messgae = Blueprint('PestMessage', __name__, url_prefix='/')


# 留言的视图
@pest_messgae.get('/pest_message')
@authorize("pest:message", log=True)
def main():
    return render_template('admin/pest/pest_message.html')


@pest_messgae.get('/pest_message/info')
def data():
    # 获取请求参数
    content = xss_escape(request.args.get('content', type=str))

    # 查询参数构造
    mf = ModelFilter()
    if content:
        mf.contains(field_name="content", value=content)

    # orm查询
    # 使用分页获取data需要.items
    mes_data = Message.query.filter(mf.get_filter(model=Message)).layui_paginate()
    count = mes_data.total
    # 返回api
    return table_api(data=model_to_dicts(schema=MesOutSchema, data=mes_data.items), count=count)


# 留言页面
@pest_messgae.get('/pest_message/add')
@authorize("message:add", log=True)
def add():
    return render_template('admin/pest/message_add.html')


# 回复页面
@pest_messgae.get('/pest_message/reply/<int:id>')
@authorize("message:reply", log=True)
def reply(id):
    mes_info = Message.query.get(id)
    return render_template('admin/pest/message_reply.html', mes_info=mes_info)


# 修改问题页面
@pest_messgae.get('/pest_message/edit/<int:id>')
@authorize("message:edit", log=True)
def edit(id):
    mes_info = Message.query.get(id)
    return render_template('admin/pest/message_edit.html', mes_info=mes_info)


@pest_messgae.post('/pest_message/update')
def update():
    req_json = request.json
    id = xss_escape(req_json.get('id'))
    content = xss_escape(req_json.get('content'))

    if not content:
        return fail_api(msg="修改内容不得为空")
    Message.query.filter_by(id=id).update({'content': content,
                                           'create_at': datetime.datetime.now()
                                           })
    db.session.commit()
    return success_api(msg="修改成功")


@pest_messgae.post('/pest_message/replymes')
@authorize("message:reply", log=True)
def replymes():
    req_json = request.json
    id = xss_escape(req_json.get('id'))
    content = xss_escape(req_json.get('content'))
    reply = xss_escape(req_json.get('reply'))

    mes_info = Message.query.filter_by(id=id, content=content).first()

    print("查到的原信息", mes_info)

    replayName = current_user.realname
    replayTime = datetime.datetime.now()

    if not reply:
        return fail_api(msg="回复内容不得为空")

    Message.query.filter_by(id=id, content=content).update({'id': mes_info.id,
                                                            'content': mes_info.content,
                                                            'reply': reply,
                                                            'userid': mes_info.userid,
                                                            'repid': replayName,
                                                            'create_at': mes_info.create_at,
                                                            'update_at': replayTime,
                                                            'isreply': 1
                                                            })
    db.session.commit()
    return success_api(msg="回复成功")


@pest_messgae.post('/pest_message/save')
@authorize("message:add", log=True)
def save():
    req_json = request.json
    content = xss_escape(req_json.get('content'))
    reply = ''
    userid = current_user.realname
    repid = ''
    create_at = datetime.datetime.now()
    update_at = ''
    isreply = 0

    if not content:
        return fail_api(msg="问题内容不得为空")

    entry = Message(content, reply, userid, repid, create_at, isreply)
    db.session.add(entry)
    db.session.commit()
    return success_api(msg="留言成功")


# 删除wiki
@pest_messgae.delete('/pest_message/remove/<int:id>')
@authorize("message:remove", log=True)
def delete(id):

    mes_info = Message.query.filter_by(id=id).first()

    if mes_info.isreply == 1:
        return fail_api(msg="已回复留言不可删除")

    res = Message.query.filter_by(id=id).delete()

    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


# 批量删除
@pest_messgae.delete('/pest_message/batchRemove')
@authorize("message:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        res = Message.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")
